import type {
  Registry,
  RegistryItem,
  registryItemTypeSchema,
} from 'shadcn-vue/schema'
import type { z } from 'zod'
import { existsSync, promises as fs } from 'node:fs'
import { template } from 'es-toolkit/compat'
import path from 'pathe'
import { rimraf } from 'rimraf'
import {
  registryItemSchema,
  registrySchema,
} from 'shadcn-vue/schema'
import { registry } from '../src/registry'
import { buildRegistry as crawlContent } from '../src/registry/crawl-content'
import { baseColors, baseColorsV4 } from '../src/registry/registry-base-colors'
import { registryCategories } from '../src/registry/registry-categories'
import { colorMapping, colors } from '../src/registry/registry-colors'
import { iconLibraries, icons } from '../src/registry/registry-icons'
import { styles } from '../src/registry/registry-styles'
// import { fixImport } from "./fix-import"

type RegistryEntry = z.infer<typeof registryItemSchema>

const METADATA_NAME = 'metadata.json'
const REGISTRY_PATH = path.join(process.cwd(), 'src/public/r')

const REGISTRY_INDEX_WHITELIST: z.infer<typeof registryItemTypeSchema>[] = [
  'registry:ui',
  'registry:lib',
  'registry:hook',
  'registry:theme',
  'registry:block',
  'registry:example',
  'registry:internal',
  'registry:style',
]

// ----------------------------------------------------------------------------
// Sync styles
// ----------------------------------------------------------------------------
async function syncStyles() {
  const sourceStyle = 'new-york'
  const targetStyle = 'default'

  const syncDirectories = ['blocks', 'composables', 'internal', 'lib', 'charts']

  // Clean up sync directories.
  for (const dir of syncDirectories) {
    rimraf.sync(path.join('registry', targetStyle, dir))
  }

  for (const item of registry.items) {
    if (
      !REGISTRY_INDEX_WHITELIST.includes(item.type)
      && item.type !== 'registry:ui'
    ) {
      continue
    }

    const resolveFiles = item.files?.map(
      file =>
        `src/registry/${sourceStyle}/${typeof file === 'string' ? file : file.path}`,
    )
    if (!resolveFiles) {
      continue
    }

    // Copy files to target style if they don't exist.
    for (const file of resolveFiles) {
      const sourcePath = path.join(process.cwd(), file)
      const targetPath = path.join(
        process.cwd(),
        file.replace(sourceStyle, targetStyle),
      )

      if (!existsSync(targetPath)) {
        // Create directory if it doesn't exist.
        await fs.mkdir(path.dirname(targetPath), { recursive: true })
        await fs.copyFile(sourcePath, targetPath)

        // Replace all @/registry/new-york/ with @/registry/default/.
        const content = await fs.readFile(targetPath, 'utf8')
        const fixedContent = content.replace(
          new RegExp(`@/registry/${sourceStyle}/`, 'g'),
          `@/registry/${targetStyle}/`,
        )
        await fs.writeFile(targetPath, fixedContent, 'utf8')
      }
    }
  }
}

// ----------------------------------------------------------------------------
// Build __registry__/index.ts.
// ----------------------------------------------------------------------------
async function buildRegistry(registry: Registry) {
  let index = `/* eslint-disable ts/ban-ts-comment */
// @ts-nocheck
// This file is autogenerated by scripts/build-registry.ts
// Do not edit this file directly.

export const Index: Record<string, any> = {
`

  for (const style of styles) {
    const itemSet = new Set<string>()
    index += `  "${style.name}": {`

    // Build style index.
    for (const item of registry.items) {
      if (itemSet.has(item.name))
        continue
      itemSet.add(item.name)

      const resolveFiles = item.files?.map(
        file =>
          `registry/${style.name}/${
            typeof file === 'string' ? file : file.path
          }`,
      )
      if (!resolveFiles) {
        continue
      }

      // Validate categories.
      if (item.categories) {
        const invalidCategories = item.categories.filter(
          category => !registryCategories.some(c => c.slug === category),
        )

        if (invalidCategories.length > 0) {
          console.error(
            `${item.name} has invalid categories: ${invalidCategories}`,
          )
          process.exit(1)
        }
      }

      const type = item.type.split(':')[1]
      const sourceFilename = ''

      let componentPath = `@/registry/${style.name}/${type}/${item.name}`

      if (item.files) {
        const files = item.files.map(file =>
          typeof file === 'string'
            ? { type: 'registry:page', path: file }
            : file,
        )
        if (files?.length) {
          componentPath = `@/registry/${style.name}/${files[0]!.path}`
        }
      }

      index += `
    "${item.name}": {
      name: "${item.name}",
      description: "${item.description ?? ''}",
      type: "${item.type}",
      registryDependencies: ${JSON.stringify(item.registryDependencies)},
      files: [${item.files?.filter(file => !file.path.includes(METADATA_NAME))?.map((file) => {
        const filePath = `registry/${style.name}/${
          typeof file === 'string' ? file : file.path
        }`
        const resolvedFilePath = path.resolve(filePath)
        return typeof file === 'string'
          ? `"${resolvedFilePath}"`
          : `{
        path: "${filePath}",
        type: "${file.type}",
        target: "${file.target ?? ''}"
      }`
      })}],
      component: () => import("${componentPath}").then((m) => m.default),
      source: "${sourceFilename}",
      categories: ${JSON.stringify(item.categories ?? [])}
    },`
    }

    index += `
  },`
  }

  index += `
}
`

  // ----------------------------------------------------------------------------
  // Build registry/index.json.
  // ----------------------------------------------------------------------------
  const items = registry.items
    .filter((item: RegistryItem) => ['registry:ui'].includes(item.type))
    .map((item) => {
      return {
        ...item,
        files: item.files?.filter(file => !file.path.includes(METADATA_NAME))?.map((_file) => {
          const file = { path: _file.path, type: item.type }
          return file
        }),
      }
    })
  const registryJson = JSON.stringify(items, null, 2)
  rimraf.sync(path.join(REGISTRY_PATH, 'index.json'))
  await writeFile(
    path.join(REGISTRY_PATH, 'index.json'),
    registryJson,
  )

  // Write style index.
  rimraf.sync(path.join(process.cwd(), '__registry__/index.ts'))
  await writeFile(path.join(process.cwd(), '__registry__/index.ts'), index)
}

// ----------------------------------------------------------------------------
// Build __registry__/block.ts.
// ----------------------------------------------------------------------------
// async function buildBlockRegistry(registryItems: RegistryItem[]) {
//   let index = `/* eslint-disable ts/ban-ts-comment */
// // @ts-nocheck
// // This file is autogenerated by scripts/build-registry.ts
// // Do not edit this file directly.

// export const Index: Record<string, any> = {
// `

//   for (const style of styles) {
//     const itemSet = new Set<string>()
//     index += `  "${style.name}": {`

//     // Build style index.
//     for (const item of registryItems) {
//       if (item.type !== 'registry:block')
//         continue

//       if (itemSet.has(item.name))
//         continue
//       itemSet.add(item.name)

//       const resolveFiles = item.files?.map(
//         file =>
//           `registry/${style.name}/${
//             typeof file === 'string' ? file : file.path
//           }`,
//       )
//       if (!resolveFiles) {
//         continue
//       }

//       const type = item.type.split(':')[1]

//       let componentPath = `@/registry/${style.name}/${type}/${item.name}`

//       if (item.files) {
//         const files = item.files.map(file =>
//           typeof file === 'string'
//             ? { type: 'registry:page', path: file }
//             : file,
//         )
//         if (files?.length) {
//           componentPath = `@/registry/${style.name}/${files[0].path}`
//         }
//       }

//       index += `
//     "${item.name}": {
//       name: "${item.name}",
//       description: "${item.description ?? ''}",
//       type: "${item.type}",
//       registryDependencies: ${JSON.stringify(item.registryDependencies)},
//       files: [${item.files?.map((file) => {
//         const filePath = `registry/${style.name}/${
//           typeof file === 'string' ? file : file.path
//         }`
//         const resolvedFilePath = path.resolve(filePath)
//         return typeof file === 'string'
//           ? `"${resolvedFilePath}"`
//           : `{
//         path: "${filePath}",
//         type: "${file.type}",
//         target: "${file.target ?? ''}",
//         raw: () => import("@/${filePath}?raw").then((m) => m.default)
//       }`
//       })}],
//       component: () => import("${componentPath}").then((m) => m.default),
//       raw: () => import("${componentPath}?raw").then((m) => m.default),
//       source: "",
//       categories: ${JSON.stringify(item.categories ?? [])}
//     },`
//     }

//     index += `
//   },`
//   }

//   index += `
// }
// `

//   // Write style block.
//   rimraf.sync(path.join(process.cwd(), '__registry__/block.ts'))
//   await writeFile(path.join(process.cwd(), '__registry__/block.ts'), index)
// }

// ----------------------------------------------------------------------------
// Build registry/styles/[style]/[name].json.
// ----------------------------------------------------------------------------
async function buildStyles(registry: Registry) {
  for (const style of styles) {
    const targetPath = path.join(REGISTRY_PATH, 'styles', style.name)

    // Create directory if it doesn't exist.
    if (!existsSync(targetPath)) {
      await fs.mkdir(targetPath, { recursive: true })
    }

    // Build registry.json for this style
    const styleRegistryItems = []

    for (const item of registry.items) {
      if (!REGISTRY_INDEX_WHITELIST.includes(item.type)) {
        continue
      }

      let metadata: RegistryEntry = {} as any
      let files
      if (item.files) {
        // get metadata.json index and exclude from `files`
        const metadataIndex = item.files.findIndex(_file => _file.path.includes(METADATA_NAME))
        if (metadataIndex !== -1) {
          metadata = JSON.parse(item?.files?.[metadataIndex]?.content ?? '{}')
        }

        files = await Promise.all(
          item.files.filter((_, index) => index !== metadataIndex).map(async (_file) => {
            const file = {
              path: _file.path,
              type: _file.type,
              content: '',
              target: _file.target ?? '',
            }

            let content: string
            try {
              content = await fs.readFile(
                path.join(process.cwd(), 'src', 'registry', style.name, file.path),
                'utf8',
              )
            }
            catch (error) {
              return
            }

            const target = file.target || ''

            return {
              path: file.path,
              type: file.type,
              content,
              target,
            }
          }),
        )
      }

      const payload = registryItemSchema
        .safeParse({
          ...metadata,
          ...item,
          files,
        })

      if (payload.success) {
        await writeFile(
          path.join(targetPath, `${item.name}.json`),
          JSON.stringify(payload.data, null, 2),
        )

        // Add item to style registry with fixed paths (without content)
        styleRegistryItems.push({
          ...item,
          files: files
            ?.map((file: any) => {
              if (!file)
                return null
              // Exclude content from registry.json
              const { content, ...fileWithoutContent } = file
              return {
                ...fileWithoutContent,
                path: `src/registry/${style.name}/${file.path}`,
              }
            })
            .filter(Boolean),
        })
      }
    }

    // Build registry.json for this style following registrySchema format
    const styleRegistry = {
      name: registry.name,
      homepage: registry.homepage,
      items: styleRegistryItems,
    }

    // Validate against registrySchema
    const validatedRegistry = registrySchema.safeParse(styleRegistry)
    if (validatedRegistry.success) {
      const styleRegistryJson = JSON.stringify(validatedRegistry.data, null, 2)
      await writeFile(
        path.join(targetPath, 'registry.json'),
        styleRegistryJson,
      )
    }
    else {
      console.error(
        `Failed to validate registry for style ${style.name}:`,
        validatedRegistry.error,
      )
    }
  }

  // ----------------------------------------------------------------------------
  // Build registry/styles/index.json.
  // ----------------------------------------------------------------------------
  const stylesJson = JSON.stringify(styles, null, 2)
  await writeFile(
    path.join(REGISTRY_PATH, 'styles/index.json'),
    stylesJson,
  )
}

// ----------------------------------------------------------------------------
// Build registry/styles/[name]/index.json.
// ----------------------------------------------------------------------------
async function buildStylesIndex() {
  for (const style of styles) {
    const targetPath = path.join(REGISTRY_PATH, 'styles', style.name)

    const payload: RegistryEntry = {
      name: style.name,
      type: 'registry:style',
      dependencies: [
        'tailwindcss-animate',
        'class-variance-authority',
        'lucide-vue-next',
      ],
      registryDependencies: ['utils'],
      tailwind: {
        config: {
          plugins: [`require("tailwindcss-animate")`],
        },
      },
      cssVars: {},
      files: [],
    }

    await writeFile(
      path.join(targetPath, 'index.json'),
      JSON.stringify(payload, null, 2),
    )
  }
}

// ----------------------------------------------------------------------------
// Build registry/colors/index.json.
// ----------------------------------------------------------------------------
async function buildThemes() {
  const colorsTargetPath = path.join(REGISTRY_PATH, 'colors')
  rimraf.sync(colorsTargetPath)
  if (!existsSync(colorsTargetPath)) {
    await fs.mkdir(colorsTargetPath, { recursive: true })
  }

  const colorsData: Record<string, any> = {}
  for (const [color, value] of Object.entries(colors)) {
    if (typeof value === 'string') {
      colorsData[color] = value
      continue
    }

    if (Array.isArray(value)) {
      colorsData[color] = value.map(item => ({
        ...item,
        rgbChannel: item.rgb.replace(/^rgb\((\d+),(\d+),(\d+)\)$/, '$1 $2 $3'),
        hslChannel: item.hsl.replace(
          /^hsl\(([\d.]+),([\d.]+%),([\d.]+%)\)$/,
          '$1 $2 $3',
        ),
      }))
      continue
    }

    if (typeof value === 'object') {
      colorsData[color] = {
        ...value,
        rgbChannel: value.rgb.replace(/^rgb\((\d+),(\d+),(\d+)\)$/, '$1 $2 $3'),
        hslChannel: value.hsl.replace(
          /^hsl\(([\d.]+),([\d.]+%),([\d.]+%)\)$/,
          '$1 $2 $3',
        ),
      }
      continue
    }
  }

  await writeFile(
    path.join(colorsTargetPath, 'index.json'),
    JSON.stringify(colorsData, null, 2),
  )

  // ----------------------------------------------------------------------------
  // Build registry/colors/[base].json.
  // ----------------------------------------------------------------------------
  const BASE_STYLES = `@tailwind base;
@tailwind components;
@tailwind utilities;
  `

  const BASE_STYLES_WITH_VARIABLES = `@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  :root {
    --background: <%- colors.light["background"] %>;
    --foreground: <%- colors.light["foreground"] %>;
    --card: <%- colors.light["card"] %>;
    --card-foreground: <%- colors.light["card-foreground"] %>;
    --popover: <%- colors.light["popover"] %>;
    --popover-foreground: <%- colors.light["popover-foreground"] %>;
    --primary: <%- colors.light["primary"] %>;
    --primary-foreground: <%- colors.light["primary-foreground"] %>;
    --secondary: <%- colors.light["secondary"] %>;
    --secondary-foreground: <%- colors.light["secondary-foreground"] %>;
    --muted: <%- colors.light["muted"] %>;
    --muted-foreground: <%- colors.light["muted-foreground"] %>;
    --accent: <%- colors.light["accent"] %>;
    --accent-foreground: <%- colors.light["accent-foreground"] %>;
    --destructive: <%- colors.light["destructive"] %>;
    --destructive-foreground: <%- colors.light["destructive-foreground"] %>;
    --border: <%- colors.light["border"] %>;
    --input: <%- colors.light["input"] %>;
    --ring: <%- colors.light["ring"] %>;
    --radius: 0.5rem;
    --chart-1: <%- colors.light["chart-1"] %>;
    --chart-2: <%- colors.light["chart-2"] %>;
    --chart-3: <%- colors.light["chart-3"] %>;
    --chart-4: <%- colors.light["chart-4"] %>;
    --chart-5: <%- colors.light["chart-5"] %>;
  }

  .dark {
    --background: <%- colors.dark["background"] %>;
    --foreground: <%- colors.dark["foreground"] %>;
    --card: <%- colors.dark["card"] %>;
    --card-foreground: <%- colors.dark["card-foreground"] %>;
    --popover: <%- colors.dark["popover"] %>;
    --popover-foreground: <%- colors.dark["popover-foreground"] %>;
    --primary: <%- colors.dark["primary"] %>;
    --primary-foreground: <%- colors.dark["primary-foreground"] %>;
    --secondary: <%- colors.dark["secondary"] %>;
    --secondary-foreground: <%- colors.dark["secondary-foreground"] %>;
    --muted: <%- colors.dark["muted"] %>;
    --muted-foreground: <%- colors.dark["muted-foreground"] %>;
    --accent: <%- colors.dark["accent"] %>;
    --accent-foreground: <%- colors.dark["accent-foreground"] %>;
    --destructive: <%- colors.dark["destructive"] %>;
    --destructive-foreground: <%- colors.dark["destructive-foreground"] %>;
    --border: <%- colors.dark["border"] %>;
    --input: <%- colors.dark["input"] %>;
    --ring: <%- colors.dark["ring"] %>;
    --chart-1: <%- colors.dark["chart-1"] %>;
    --chart-2: <%- colors.dark["chart-2"] %>;
    --chart-3: <%- colors.dark["chart-3"] %>;
    --chart-4: <%- colors.dark["chart-4"] %>;
    --chart-5: <%- colors.dark["chart-5"] %>;
  }
}

@layer base {
  * {
    @apply border-border;
  }
  body {
    @apply bg-background text-foreground;
  }
}`

  for (const baseColor of ['slate', 'gray', 'zinc', 'neutral', 'stone']) {
    const base: Record<string, any> = {
      inlineColors: {},
      cssVars: {},
    }
    for (const [mode, values] of Object.entries(colorMapping)) {
      base.inlineColors[mode] = {}
      base.cssVars[mode] = {}
      for (const [key, value] of Object.entries(values)) {
        if (typeof value === 'string') {
          // Chart colors do not have a 1-to-1 mapping with tailwind colors.
          if (key.startsWith('chart-')) {
            base.cssVars[mode][key] = value
            continue
          }

          const resolvedColor = value.replace(/\{\{base\}\}-/g, `${baseColor}-`)
          base.inlineColors[mode][key] = resolvedColor

          const [resolvedBase, scale] = resolvedColor.split('-')
          const color = scale
            ? colorsData[resolvedBase!].find(
                (item: any) => item.scale === Number.parseInt(scale),
              )
            : colorsData[resolvedBase!]
          if (color) {
            base.cssVars[mode][key] = color.hslChannel
          }
        }
      }
    }

    // Add v4 css vars.
    base.cssVarsV4 = baseColorsV4[baseColor as keyof typeof baseColorsV4]

    // Build css vars.
    base.inlineColorsTemplate = template(BASE_STYLES)({})
    base.cssVarsTemplate = template(BASE_STYLES_WITH_VARIABLES)({
      colors: base.cssVars,
    })

    await writeFile(
      path.join(REGISTRY_PATH, `colors/${baseColor}.json`),
      JSON.stringify(base, null, 2),
    )

    // ----------------------------------------------------------------------------
    // Build registry/themes.css
    // ----------------------------------------------------------------------------
    const THEME_STYLES_WITH_VARIABLES = `
.theme-<%- theme %> {
  --background: <%- colors.light["background"] %>;
  --foreground: <%- colors.light["foreground"] %>;

  --muted: <%- colors.light["muted"] %>;
  --muted-foreground: <%- colors.light["muted-foreground"] %>;

  --popover: <%- colors.light["popover"] %>;
  --popover-foreground: <%- colors.light["popover-foreground"] %>;

  --card: <%- colors.light["card"] %>;
  --card-foreground: <%- colors.light["card-foreground"] %>;

  --border: <%- colors.light["border"] %>;
  --input: <%- colors.light["input"] %>;

  --primary: <%- colors.light["primary"] %>;
  --primary-foreground: <%- colors.light["primary-foreground"] %>;

  --secondary: <%- colors.light["secondary"] %>;
  --secondary-foreground: <%- colors.light["secondary-foreground"] %>;

  --accent: <%- colors.light["accent"] %>;
  --accent-foreground: <%- colors.light["accent-foreground"] %>;

  --destructive: <%- colors.light["destructive"] %>;
  --destructive-foreground: <%- colors.light["destructive-foreground"] %>;

  --ring: <%- colors.light["ring"] %>;

  --radius: <%- colors.light["radius"] %>;
}

.dark .theme-<%- theme %> {
  --background: <%- colors.dark["background"] %>;
  --foreground: <%- colors.dark["foreground"] %>;

  --muted: <%- colors.dark["muted"] %>;
  --muted-foreground: <%- colors.dark["muted-foreground"] %>;

  --popover: <%- colors.dark["popover"] %>;
  --popover-foreground: <%- colors.dark["popover-foreground"] %>;

  --card: <%- colors.dark["card"] %>;
  --card-foreground: <%- colors.dark["card-foreground"] %>;

  --border: <%- colors.dark["border"] %>;
  --input: <%- colors.dark["input"] %>;

  --primary: <%- colors.dark["primary"] %>;
  --primary-foreground: <%- colors.dark["primary-foreground"] %>;

  --secondary: <%- colors.dark["secondary"] %>;
  --secondary-foreground: <%- colors.dark["secondary-foreground"] %>;

  --accent: <%- colors.dark["accent"] %>;
  --accent-foreground: <%- colors.dark["accent-foreground"] %>;

  --destructive: <%- colors.dark["destructive"] %>;
  --destructive-foreground: <%- colors.dark["destructive-foreground"] %>;

  --ring: <%- colors.dark["ring"] %>;
}`

    const themeCSS = []
    for (const theme of baseColors) {
      themeCSS.push(
        template(THEME_STYLES_WITH_VARIABLES)({
          colors: theme.cssVars,
          theme: theme.name,
        }),
      )
    }

    await writeFile(
      path.join(REGISTRY_PATH, `themes.css`),
      themeCSS.join('\n'),
    )

    // ----------------------------------------------------------------------------
    // Build registry/themes/[theme].json
    // ----------------------------------------------------------------------------
    rimraf.sync(path.join(REGISTRY_PATH, 'themes'))
    for (const baseColor of ['slate', 'gray', 'zinc', 'neutral', 'stone']) {
      const payload: Record<string, any> = {
        name: baseColor,
        label: baseColor.charAt(0).toUpperCase() + baseColor.slice(1),
        cssVars: {},
      }
      for (const [mode, values] of Object.entries(colorMapping)) {
        payload.cssVars[mode] = {}
        for (const [key, value] of Object.entries(values)) {
          if (typeof value === 'string') {
            const resolvedColor = value.replace(/\{\{base\}\}-/g, `${baseColor}-`)
            payload.cssVars[mode][key] = resolvedColor

            const [resolvedBase, scale] = resolvedColor.split('-')
            const color = scale
              ? colorsData[resolvedBase!].find(
                  (item: any) => item.scale === Number.parseInt(scale),
                )
              : colorsData[resolvedBase!]
            if (color) {
              payload.cssVars[mode][key] = color.hslChannel
            }
          }
        }
      }

      const targetPath = path.join(REGISTRY_PATH, 'themes')

      // Create directory if it doesn't exist.
      if (!existsSync(targetPath)) {
        await fs.mkdir(targetPath, { recursive: true })
      }

      await writeFile(
        path.join(targetPath, `${payload.name}.json`),
        JSON.stringify(payload, null, 2),
      )
    }
  }
}

// ----------------------------------------------------------------------------
// Build registry/icons/index.json.
// ----------------------------------------------------------------------------
async function buildIcons() {
  const iconsTargetPath = path.join(REGISTRY_PATH, 'icons')
  rimraf.sync(iconsTargetPath)
  if (!existsSync(iconsTargetPath)) {
    await fs.mkdir(iconsTargetPath, { recursive: true })
  }

  const iconsData = icons

  await writeFile(
    path.join(iconsTargetPath, 'index.json'),
    JSON.stringify(iconsData, null, 2),
  )
}

// ----------------------------------------------------------------------------
// Build __registry__/icons.ts.
// ----------------------------------------------------------------------------
async function buildRegistryIcons() {
  let index = `/* eslint-disable ts/ban-ts-comment */
// @ts-nocheck
// This file is autogenerated by scripts/build-registry.ts
// Do not edit this file directly.
import * as React from "react"

export const Icons = {
`

  for (const [icon, libraries] of Object.entries(icons)) {
    index += `  "${icon}": {`
    for (const [library, componentName] of Object.entries(libraries)) {
      const packageName = iconLibraries[library as keyof typeof iconLibraries].package
      if (packageName) {
        index += `
  ${library}:  () => import("${packageName}").then(mod => ({
    default: mod.${componentName}
  })),`
      }
    }
    index += `
},`
  }

  index += `
}
`

  // Write style index.
  rimraf.sync(path.join(process.cwd(), '__registry__/icons.ts'))
  await writeFile(
    path.join(process.cwd(), '__registry__/icons.ts'),
    index,
  )
}

// ----------------------------------------------------------------------------
// Generate individual registry files from crawled content
// ----------------------------------------------------------------------------
async function generateRegistryFiles(allItems: RegistryItem[]) {
  // Separate items by type
  const ui = allItems.filter(item => item.type === 'registry:ui')
  const blocks = allItems.filter(item =>
    item.type === 'registry:block' && !item.name.includes('chart'),
  )
  const charts = allItems.filter(item =>
    item.type === 'registry:block' && item.name.includes('chart'),
  )
  const composables = allItems.filter(item => item.type === 'registry:composable')
  const examples = allItems.filter(item => item.type === 'registry:example')
  const lib = allItems.filter(item => item.type === 'registry:lib')

  // Generate registry files
  await Promise.all([
    generateRegistryFile('registry-ui.ts', 'ui', ui),
    generateRegistryFile('registry-blocks.ts', 'blocks', blocks),
    generateRegistryFile('registry-charts.ts', 'charts', charts),
    generateRegistryFile('registry-composables.ts', 'composables', composables),
    generateRegistryFile('registry-examples.ts', 'examples', examples),
    generateRegistryFile('registry-lib.ts', 'lib', lib),
  ])

  // eslint-disable-next-line no-console
  console.log('✅ Registry files generated successfully!')
  // eslint-disable-next-line no-console
  console.log(`📊 Generated ${allItems.length} registry items:`)
  // eslint-disable-next-line no-console
  console.log(`   - UI Components: ${ui.length}`)
  // eslint-disable-next-line no-console
  console.log(`   - Blocks: ${blocks.length}`)
  // eslint-disable-next-line no-console
  console.log(`   - Charts: ${charts.length}`)
  // eslint-disable-next-line no-console
  console.log(`   - Composables: ${composables.length}`)
  // eslint-disable-next-line no-console
  console.log(`   - Examples: ${examples.length}`)
  // eslint-disable-next-line no-console
  console.log(`   - Lib: ${lib.length}`)
}

async function generateRegistryFile(filename: string, exportName: string, items: RegistryItem[]) {
  const content = `import type { RegistryItem } from "shadcn-vue/schema"

export const ${exportName}: RegistryItem[] = ${JSON.stringify(items, null, 2)}
`

  const filePath = path.join(process.cwd(), 'src/registry', filename)
  await writeFile(filePath, content)
  // eslint-disable-next-line no-console
  console.log(`📝 Generated ${filename} with ${items.length} items`)
}

async function writeFile(path: string, payload: any) {
  return fs.writeFile(
    path,
    `${payload}\r\n`,
    'utf8',
  )
}

async function syncRegistry() {
  // Copy the public/r directory to v4/public/r without triggering v4's build
  const wwwPublicR = path.resolve(process.cwd(), 'src/public/r')
  const v4PublicR = path.resolve(process.cwd(), '../../apps/v4/public/r')

  // Ensure the source directory exists
  if (!existsSync(wwwPublicR)) {
    await fs.mkdir(wwwPublicR, { recursive: true })
  }

  // Clean and recreate the v4/public/r directory
  rimraf.sync(v4PublicR)
  await fs.mkdir(v4PublicR, { recursive: true })

  // Copy files from www to v4
  await fs.cp(wwwPublicR, v4PublicR, { recursive: true })
}

try {
  const content = await crawlContent()
  const allItems = [...registry.items, ...content]
  const crawlResult = { success: true, data: allItems }

  // Local check
  // TODO: remove
  await writeFile(
    path.join(REGISTRY_PATH, 'temp.json'),
    JSON.stringify(crawlResult.data ?? '', null, 2),
  )

  if (!crawlResult.success) {
    console.error('Failed to parse registry data')
    process.exit(1)
  }

  // Generate individual registry files from crawled content
  await generateRegistryFiles(crawlResult.data)

  console.log('💽 Building registry...')
  const result = registrySchema.safeParse(registry)

  if (!result.success) {
    console.error(result.error)
    process.exit(1)
  }

  await syncStyles()
  await buildRegistry(result.data)
  await buildStyles(result.data)
  // await buildStylesIndex()
  await buildThemes()

  await buildRegistryIcons()
  await buildIcons()

  console.log('🔄 Syncing registry...')
  await syncRegistry()

  console.log('✅ Done!')
  process.exit(0)
}
catch (error) {
  console.error(error)
  process.exit(1)
}
